package com.xishu.service;


import com.xishu.cash.QfPayClient;
import com.xishu.config.Constant;
import com.xishu.entity.order.Order;
import com.xishu.entity.shop.Shop;
import com.xishu.service.order.base.OrderService;
import com.xishu.util.AES;
import com.xishu.util.Tools;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 支付服务
 */
public class PayService implements Tools {
    private static PayService instance = new PayService();
    private static Logger logger = LoggerFactory.getLogger(PayService.class);
    private CommonService commonService = CommonService.getInstance();

    private PayService() {
    }

    public static PayService getInstance() {
        return instance;
    }

    /**
     * 订单退款，真实退款
     *
     * @param order
     */
    public void refund(Order order) throws Exception {
        if (order == null) {
            logger.info("order is empty");
            return;
        }

        Integer payType = order.getPayType();

        if (payType == null) {
            logger.info("pay type is empty");
            return;
        }


        //已经退费的订单不能再退费
        if (getBoolean(order.getReturnCash())) {
            logger.info("order already return cash");
            return;
        }

        Long shopId = order.getShopId();

        Shop shop = ShopService.getInstance().findShopById(shopId);

        String qfCode = AES.decrypt(shop.getQfCode());
        String qfKey = AES.decrypt(shop.getQfKey());
        String qfSid = shop.getQfSid();

        //微信，支付宝，用QF退款
        if (payType == Constant.ORDER_PAY_TYPE_WEIXIN || payType == Constant.ORDER_PAY_TYPE_ALIPAY) {
            QfPayClient qfPayClient = new QfPayClient(qfCode, qfKey, qfSid);
            //只是支付订单，那么只退款当前订单
            if (order.getParentOrderId() != null) {
                logger.info("will return {} order cash ", order.getId());
                String returnPaymentResult = qfPayClient.returnPayment(order);
                JSONObject jsonObject = JSONObject.fromObject(returnPaymentResult);
                String statusResult = jsonObject.getString("respcd");
                boolean payResult = equals(statusResult, "0000");

                //成功退款，设置标记
                if (payResult) {
                    logger.info("will set order return cash flag");
                    order.setReturnCash(true);
                    commonService.save(order);
                } else {
                    logger.info("order turn cash failed");
                }
            } else {
                //总订单，那么需要将所有的子订单都退款
                List<Order> orderList = OrderService.getInstance().findOrderByParentId(order.getId(), order.getShopId());
                for (Order subOrder : orderList) {
                    //递归退款
                    refund(subOrder);
                }
            }
        }

    }
}
